strings.bash

#!/usr/bin/env bash

uniq_counter=0

__FILE__(){
    echo "${BASH_SOURCE[1]}"
}
__DIR__(){
    echo "$(dirname ${BASH_SOURCE[1]})"
}

uniqid() {
    uniq_counter=$((uniq_counter + 1))
    echo "$(date +%N)-${uniq_counter}"
}

expand_tilde_path() {
    # See https://stackoverflow.com/a/29310477/802469 where this solution came from
    local path
    local -a pathElements resultPathElements
    IFS=':' read -r -a pathElements <<<"$1"
    : "${pathElements[@]}"
    for path in "${pathElements[@]}"; do
        : "$path"
        case $path in
        "~+"/*)
            path=$PWD/${path#"~+/"}
            ;;
        "~-"/*)
            path=$OLDPWD/${path#"~-/"}
            ;;
        "~"/*)
            path=$HOME/${path#"~/"}
            ;;
        "~"*)
            username=${path%%/*}
            username=${username#"~"}
            IFS=: read -r _ _ _ _ _ homedir _ < <(getent passwd "$username")
            if [[ $path = */* ]]; then
            path=${homedir}/${path#*/}
            else
            path=$homedir
            fi
            ;;
        esac
        resultPathElements+=( "$path" )
    done
    local result
    printf -v result '%s:' "${resultPathElements[@]}"
    printf '%s\n' "${result%:}"
}

##
#
# @tip create an array of all lines in a string & store the result in a variable
# @example str_split_lines "multi line string" lines
# @arg a string 
# @arg a name of a variable to store the result in
#
function str_split_line(){
# for IFS, see https://stackoverflow.com/questions/16831429/when-setting-ifs-to-split-on-newlines-why-is-it-necessary-to-include-a-backspac
# IFS=$(msg -n "\n")
#IFS=$'\n'
IFS="
"
    declare -n SPLIT_LINES_VAR_INTERNAL=$2
    while read "line"; do
        SPLIT_LINES_VAR_INTERNAL+=("${line}")
    done <<< "${1}"
}

str_trim(){
    local trimmed;
    trimmed=$(echo "$1" | sed -e 's/^\s*//')
    trimmed=$(echo "$trimmed" | sed -e 's/\s*$//')
    echo "$trimmed"
}

remove_trail_slash(){
    local dir;
    dir="$1"
    while [[ "${dir:(-1)}" == "/" ]]; do
        dir="${dir:0:(-1)}"
    done

    echo "$dir";
}

str_len(){
    local len;
    len=$(expr length "$1")
    echo "$len"
}